package com.sskj.protocol.sskjboard.handler;

import com.sskj.common.dto.DeviceTelemetry;
import com.sskj.common.enums.DeviceTelemetryTypeEnum;
import com.sskj.protocol.sskjboard.model.FrameMessage;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

@Component
public class FrameMessageHandler {

    /**
     * 报文处理
     * @param frameMessage 报文实例
     * @return 统一物模型
     */
    public DeviceTelemetry handler(FrameMessage frameMessage) {
        if (frameMessage.getCommandType() == 0x01 && frameMessage.getCommandCode() == 0x02) {
            return registerHandler(frameMessage);
        } else if (frameMessage.getCommandType() == 0x01 && frameMessage.getCommandCode() == 0x01) {
            return heartbeatHandler(frameMessage);
        }

        return null;
    }

    /**
     * 注册报文处理
     * @param frameMessage 报文
     * @return 统一物模型
     */
    private DeviceTelemetry registerHandler(FrameMessage frameMessage) {
        DeviceTelemetry deviceTelemetry = new DeviceTelemetry();
        deviceTelemetry.setType(DeviceTelemetryTypeEnum.ONLINE.getType());
        deviceTelemetry.setProperties(null);
        deviceTelemetry.setTimestamp(Instant.now().toEpochMilli());

        return deviceTelemetry;
    }

    /**
     * 心跳报文处理
     * @param frameMessage 报文
     * @return 统一物模型
     */
    private DeviceTelemetry heartbeatHandler(FrameMessage frameMessage) {
        DeviceTelemetry deviceTelemetry = new DeviceTelemetry();
        deviceTelemetry.setType(DeviceTelemetryTypeEnum.PROPERTY.getType());

        long timestamp = Instant.now().toEpochMilli();
        Map<String, Object> properties = new HashMap<>();
        properties.put("heartbeat", timestamp);
        deviceTelemetry.setProperties(properties);
        deviceTelemetry.setTimestamp(Instant.now().toEpochMilli());

        return deviceTelemetry;
    }
}
